package com.shao.web;

import com.shao.pojo.Book;
import com.shao.pojo.Cart;
import com.shao.pojo.CartItem;
import com.shao.service.BookService;
import com.shao.service.impl.BookServiceImpl;
import com.shao.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: SJP
 * Date: 2021/5/24
 * Time: 21:19
 * Description: No Description
 */
public class CartServlet extends BaseServlet {
    BookService bookService = new BookServiceImpl();

    /**
     * 加入购物车
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void addItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数，商品ID
        int id = WebUtils.parseInt(req.getParameter("id"),0);
        //调用bookService.querybookById 获取商品信息
        Book book = bookService.queryBookById(id);
        //把图书信息转化为CartItem商品项
        CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice());
        //调用Cart.addItem()
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            req.getSession().setAttribute("cart",cart);
        }
        cart.addItem(cartItem);
        //重定向到原来商品列表页面
        resp.sendRedirect(req.getHeader("Referer"));
    }
}
